resource "aws_lb_listener"
code:例.tf(rb)
resource "aws_lb_listener" "http" {
load_balancer_arn = aws_lb.example.arn
port = 80
protocol = "HTTP"
default_action {
type = "fixed-response"
fixed_response {
content_type = "text/plain"
message_body = "404: page not found"
status_code = 404
}
}
}
GPT-4.icon
AWS Load Balancer(ALB や NLB)のポートごとの処理を定義するリソース
ロードバランサーはリスナーがなければトラフィックを処理できません。
リスナーは「このポートに来たリクエストをどう処理するか」を決める設定です。
✅ aws_lb_listener の基本
table:_
項目 説明
リソース名 aws_lb_listener
目的 ロードバランサーのリスナー(ポート、プロトコル、ルーティング)を定義する
主な利用場面 HTTP/HTTPS リクエストの受信口を設定し、どのターゲットグループにルーティングするかを指定
🔍 ざっくり構造
code:hcl(rb)
resource "aws_lb_listener" "example" {
load_balancer_arn = aws_lb.example.arn
port = 80
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.example.arn
}
}
🎯 主なパラメータ
table:_
パラメータ 説明
load_balancer_arn 紐づけるロードバランサーの ARN
port リッスンするポート番号(例:80, 443)
protocol 使用するプロトコル(HTTP、HTTPS、TCP など)
ssl_policy HTTPS の場合のセキュリティポリシー
certificate_arn HTTPS の場合の ACM 証明書 ARN
default_action リクエストに対して実行するアクション(基本は forward)
🔐 HTTPS の場合
code:hcl(rb)
resource "aws_lb_listener" "https" {
load_balancer_arn = aws_lb.example.arn
port = 443
protocol = "HTTPS"
ssl_policy = "ELBSecurityPolicy-2016-08"
certificate_arn = aws_acm_certificate.example.arn
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.example.arn
}
}
HTTPS の場合、ssl_policy と certificate_arn は 必須
ssl_policy は ALB が提供する TLS 設定プリセット
⚙️ default_action の主なタイプ
table:_
type 説明
forward ターゲットグループへリクエストを転送
redirect HTTP から HTTPS へのリダイレクト等
fixed-response 固定レスポンスを返す(メンテナンス画面など)
例: HTTP → HTTPS リダイレクト
code:hcl(rb)
resource "aws_lb_listener" "http" {
load_balancer_arn = aws_lb.example.arn
port = 80
protocol = "HTTP"
default_action {
type = "redirect"
redirect {
port = "443"
protocol = "HTTPS"
status_code = "HTTP_301"
}
}
}
例: 固定レスポンス
code:hcl(rb)
resource "aws_lb_listener" "fixed" {
load_balancer_arn = aws_lb.example.arn
port = 80
protocol = "HTTP"
default_action {
type = "fixed-response"
fixed_response {
content_type = "text/plain"
message_body = "Service under maintenance"
status_code = "503"
}
}
}